package com.xjscrm.console.config;

import com.uzai.trace.TraceIdThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author jianghan
 * @date 2017-11-09 17:01
 */
@Configuration
@EnableAsync
public class TaskExecutorConfig {
    private int corePoolSize = 100;
    private int maxPoolSize = 300;
    private int queueCapacity = 8;
    private int keepAlive = 60;

    @Bean
    public Executor taskExecutor() {
        TraceIdThreadPoolExecutor executor = new TraceIdThreadPoolExecutor(corePoolSize, maxPoolSize, keepAlive, TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueCapacity), new ThreadPoolExecutor.CallerRunsPolicy());
        CustomizableThreadFactory customizableThreadCreator = new CustomizableThreadFactory("thread-pool-");
        executor.setThreadFactory(customizableThreadCreator);
        return executor;
    }

    @Bean
    public Executor chatExecutor() {
        TraceIdThreadPoolExecutor traceIdThreadPoolExecutor = new TraceIdThreadPoolExecutor(100, 2000, 300, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10240), new ThreadPoolExecutor.CallerRunsPolicy());
        CustomizableThreadFactory customizableThreadCreator = new CustomizableThreadFactory("chat-pool-");
        traceIdThreadPoolExecutor.setThreadFactory(customizableThreadCreator);
        return traceIdThreadPoolExecutor;
    }
}
